package main

import (
	"fmt"
	"github.com/go-acme/lego/v3/log"
	"golang.org/x/net/websocket"
	"io"
	"net/http"
	"regexp"
	"sync"
	"time"
)

type Number struct {
	num     int
	chPlus  chan int
	chMinis chan int
}

//加
func (n *Number) Plus(i int, wg sync.WaitGroup) {
	defer wg.Done()
	n.chPlus <- i
}

//减
func (n *Number) Minis(i int, wg sync.WaitGroup) {
	defer wg.Done()
	n.chMinis <- i
}

func (n *Number) Res() {
	for {
		select {
		case r := <-n.chPlus:
			n.num = n.num + r
		case r := <-n.chMinis:
			n.num = n.num + r
		}

	}
}

func main_1() {

	t := &Number{
		0,
		make(chan int),
		make(chan int),
	}

	go t.Res()

	wg := sync.WaitGroup{}

	for i := 0; i < 30; i++ {
		go t.Plus(i, wg)

	}

	for i := 0; i < 20; i++ {
		go t.Minis(i, wg)
	}

	wg.Wait()

	//console.log(t.number)

}

func main2() {

	ch := make(chan bool)

	for {
		select {
		case <-time.After(time.Second * 3):
			go func() {
				ch <- true
			}()
		case <-ch:
			log.Println("ok")
		}
	}

}

func connHandler(conn *websocket.Conn) {

	io.WriteString(conn, "heihei")
}

type ConnHandler func(conn *websocket.Conn)

func middleware(handler ConnHandler) func(conn *websocket.Conn) {

	return func(conn *websocket.Conn) {

		reg, err := regexp.Compile("^/ws/[a-z0-9].*")
		if err != nil {
			fmt.Println(err)
			return
		}
		if b := reg.MatchString(conn.Request().URL.Path); b {
			handler(conn)
		} else {
			log.Println("bad request")
			conn.WriteClose(http.StatusBadRequest)
		}

	}

}

func main() {

	http.Handle("/", websocket.Handler(middleware(connHandler)))

	http.ListenAndServe(":8080", nil)

}
